package com.gtjy.maven;

import java.io.BufferedInputStream;
import java.io.File;
import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @类功能说明：  maven jar 注册
 * @类修改者：  
 * @修改日期：  
 * @修改说明： 
 * @公司名称：乌鲁木齐光通嘉业网络服务有限公司 
 * @作者：L  
 * @创建时间：2013-5-30 下午12:51:49  
 * @版本：V1.0  
 */
public class MavenRegister {
	
	private Queue<Artifact> registryQueue = new LinkedList<Artifact>();
	private String mvnHomePath = "";
	
	public void doRegister() throws Throwable{
		Runtime r = Runtime.getRuntime();
		if(!mvnHomePath.endsWith(File.separator)){
			mvnHomePath += File.separator;
		}
		
		Artifact artifact = null;
		while((artifact = registryQueue.poll()) != null){
			StringBuilder command = new StringBuilder();
			//mvn deploy:deploy-file -DgroupId=com.bea.xml -DartifactId=jsr173-ri -Dversion=1.0 -Dpackaging=jar -Dfile=[path to file] -Durl=[url] -DrepositoryId=[id]
			
			// 未测试
			if(artifact.getUrl() != null && artifact.getRepositoryId() != null){
				command.append("cmd /c ")
					.append(mvnHomePath)
					.append("mvn deploy:deploy-file -DgroupId=")
					.append(artifact.getGroupId())
					.append(" -DartifactId=")
					.append(artifact.getArtifactId())
					.append(" -Dversion=")
					.append(artifact.getVersion())
					.append(" -Dpackaging=")
					.append(artifact.getPackaging())
					.append(" -Dfile=")
					.append(artifact.getPath())
					.append(" -Durl=")
					.append(artifact.getUrl())
					.append(" DrepositoryId=")
					.append(artifact.getRepositoryId());
			}else{
				command.append("cmd /c ")
					.append(mvnHomePath)
					.append("mvn install:install-file -DgroupId=")
					.append(artifact.getGroupId())
					.append(" -DartifactId=")
					.append(artifact.getArtifactId())
					.append(" -Dversion=")
					.append(artifact.getVersion())
					.append(" -Dpackaging=")
					.append(artifact.getPackaging())
					.append(" -Dfile=")
					.append(artifact.getPath());
			}
			Process p = r.exec(command.toString());

			BufferedInputStream bis = new BufferedInputStream(p.getInputStream());
			
			byte [] data = new byte[2048];
			int len = 0;
			while ((len = bis.read(data)) != -1) {
				System.out.print(new String(data,0,len,Charset.forName("GBK")));
			}
		}
	}

	public void put(Artifact artifact) {
		this.registryQueue.offer(artifact);
	}
	
	public Queue<Artifact> getRegistryQueue() {
		return registryQueue;
	}

	public void setMvnHomePath(String mvnHomePath) {
		this.mvnHomePath = mvnHomePath;
	}
}
